/*
 * @Author: 0x9DEFA478
 * @Date: 2025-10-05 19:41:11
 * @LastEditTime: 2025-10-05 22:18:41
 * @LastEditors: 0x9DEFA478
 * @Description: 
 * 
 */
#include "./GUID.hpp"
#include "../../H_Type.hpp"
#include "../../Utility/H_String.hpp"
#include <vector>
#include <sstream>
#include <stdexcept>




namespace SystemAPI{

  namespace Windows{
#if defined(_WIN32)

    static char HexCharToUpper(char c){
      if((c>='a')&&(c<='z')){
        c-='a'-'A';
      }
      return c;
    }

    static H::byte UpperHexCharToVal(char c){
      if((c>='0')&&(c<='9')){
        return c-'0';
      }
      if((c>='A')&&(c<='F')){
        return c-'A'+0xAU;
      }
      return 0x10U;
    }

    static std::vector<std::string> SplitUUID(const std::string& UUIDString){
      std::vector<std::string> r;
      std::stringstream ss;

      for(auto& Item:UUIDString){
        if(Item=='-'){
          r.emplace_back(ss.str());
          ss=std::stringstream();
          continue;
        }
        char c=HexCharToUpper(Item);
        auto val=UpperHexCharToVal(c);

        if(val>0xFU){
          throw std::invalid_argument("UUID出现无效字符");
        }

        ss<<c;
      }

      auto str=ss.str();
      if(str.length()>0){
        r.emplace_back(str);
      }

      return r;
    }

    static H::uint32 UpperHexStringToVal(const std::string& String){
      H::uint32 r=0;

      for(auto& Item:String){
        r=(r<<4)+UpperHexCharToVal(Item);
      }
      return r;
    }

    GUID::GUID(const std::string& GUIDString){
      std::stringstream ss;

      auto len=GUIDString.length();
      std::size_t index;

      index=0;
      if(GUIDString[index]=='{'){
        index=1;
        len--;
        if(GUIDString[len]!='}'){
          throw std::invalid_argument("UUID不正确, 尾部缺少'}'");
        }
      }

      auto uuidFrame=SplitUUID(std::string(GUIDString,index,len-index));

      if(uuidFrame.size()!=5){
        throw std::invalid_argument("不完整的UUID");
      }

      guid.Data1=UpperHexStringToVal(uuidFrame[0]);
      guid.Data2=UpperHexStringToVal(uuidFrame[1]);
      guid.Data3=UpperHexStringToVal(uuidFrame[2]);

      if(uuidFrame[3].length()!=4){
        throw std::invalid_argument("UUID不正确, Bit64~79长度错误");
      }
      if(uuidFrame[4].length()!=12){
        throw std::invalid_argument("UUID不正确, Bit80~127长度错误");
      }

      auto strFrame=uuidFrame[3]+uuidFrame[4];

      for(int i=0;i<8;i++){
        guid.Data4[i]=UpperHexStringToVal(std::string(strFrame,2*i,2));
      }

    }

    std::string GUID::String()const noexcept{
      return H::String::Format("%08X-%04X-%04X-%02X%02X-%02X%02X%02X%02X%02X%02X",(unsigned int)guid.Data1,guid.Data2,guid.Data3
        ,guid.Data4[0],guid.Data4[1],guid.Data4[2],guid.Data4[3],guid.Data4[4],guid.Data4[5],guid.Data4[6],guid.Data4[7]);
    }

#endif
  }

}



